﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LybrixNursingCRMDesktop.FrameWork;
using LybrixNursingCommon;

namespace LybrixNursingCRMDesktop
{
    /// <summary>
    /// Interaction logic for SapakDetails.xaml
    /// </summary>
    public partial class SapakDetails : Page
    {
        private readonly LybrixNursingCommon.NursingDBContainer _entities;
        string sapakID;
        bool isNew = true;
        LybrixNursingCommon.Sapak currentSapak;
        public SapakDetails()
        {
            InitializeComponent();
            _entities = Repository.Entities;
            sapakID = GetUniqueID();
            SapakID.Content = sapakID;
            isNew = true;
            sapakType.ItemsSource = new List<string>() { "ריק", "פרטי", "חברה" };
            method.ItemsSource = new List<string>() { "ריק", "תשלום חד פעמי", "אחוז" };
        }

        public SapakDetails(Sapak _sapak)
        {
            InitializeComponent();
            _entities = Repository.Entities;

            currentSapak = _sapak;
            InitCusrrentSapak();
            isNew = false;
            sapakType.ItemsSource = new List<string>() { "ריק", "פרטי", "חברה" };
            method.ItemsSource = new List<string>() { "ריק", "תשלום חד פעמי", "אחוז" };
        }

        private void onSave_Click(object sender, RoutedEventArgs e)
        {
            if (!checkmandatoryFields())
                return;
            else
            {
                if (isNew)
                {
                    int type = 0;
                    int methodType = 0;

                    Sapak newSapak = new Sapak();
                    newSapak.sapakName = sapakname.Text;
                    if (sapakType.Text == "ריק")
                        type = 0;
                    if (sapakType.Text == "פרטי")
                        type = 1;
                    if (sapakType.Text == "חברה")
                        type = 2;
                    newSapak.sapakType = type;
                    newSapak.sapakID = sapakID;

                    if (method.Text == "ריק")
                    {
                        methodType = 0;
                        newSapak.percentage = 0;
                        newSapak.Amount = 0;
                    }
                    if (method.Text == "תשלום חד פעמי")
                    {
                        methodType = 1;
                        newSapak.percentage = 0;
                        newSapak.Amount = Int32.Parse((percentage.Text));
                    }
                    if (method.Text == "אחוז")
                    {
                        methodType = 2;
                        newSapak.percentage = Int32.Parse((percentage.Text));
                        newSapak.Amount = 0;
                    }
                    newSapak.methodType = methodType;

                   newSapak.userName =  userName.Text;
                   newSapak.password =  password.Password;
                   newSapak.phone =  phone1.Text;
                   newSapak.mobile = phone2.Text;
                   newSapak.area = area.Text ;

                    _entities.AddToSapaks(newSapak);
                }
                else
                {
                    int type = 0;
                    int methodType = 0;


                    currentSapak.sapakName = sapakname.Text;
                    if (sapakType.Text == "ריק")
                        type = 0;
                    if (sapakType.Text == "פרטי")
                        type = 1;
                    if (sapakType.Text == "חברה")
                        type = 2;
                    currentSapak.sapakType = type;

                    if (method.Text == "ריק")
                    {
                        methodType = 0;
                        currentSapak.percentage = 0;
                        currentSapak.Amount = 0;
                    }
                    if (method.Text == "תשלום חד פעמי")
                    {
                        methodType = 1;
                        currentSapak.percentage = 0;
                        currentSapak.Amount = Int32.Parse((percentage.Text));
                    }
                    if (method.Text == "אחוז")
                    {
                        methodType = 2;
                        currentSapak.percentage = Int32.Parse((percentage.Text));
                        currentSapak.Amount = 0;
                    }
                    currentSapak.methodType = methodType;

                    currentSapak.userName = userName.Text;
                    currentSapak.password = password.Password;
                    currentSapak.phone = phone1.Text;
                    currentSapak.mobile = phone2.Text;
                    currentSapak.area = area.Text;
                }

                try
                {

                    _entities.SaveChanges();
                    MessageBox.Show("הרשומה נרשמה בהצלחה", "הודעה", MessageBoxButton.OK);
                    NavigationCenter.ShowSearchPage(NavigationTarget.SapakPage, this);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
        }


        private void InitCusrrentSapak()
        {
            int type = 0;
            int methodType = 0;
            type = currentSapak.sapakType;
            methodType = (int)currentSapak.methodType;

            if (type == 0)
                sapakType.SelectedItem = "ריק";
            if (type == 1)
                sapakType.SelectedItem = "פרטי";
            if (type == 2)
                sapakType.SelectedItem = "חברה";
            SapakID.Content = currentSapak.sapakID;
            sapakname.Text = currentSapak.sapakName;

            if (methodType == 0)
                method.SelectedItem = "ריק";
            if (methodType == 1)
                method.SelectedItem = "תשלום חד פעמי";
            if (methodType == 2)
                method.SelectedItem = "אחוז";

            if (methodType == 0)
                percentage.Text = "0";
            if (methodType == 1)
                percentage.Text = (currentSapak.Amount).ToString();
            if (methodType == 2)
                percentage.Text = (currentSapak.percentage).ToString();

            userName.Text = currentSapak.userName;
            password.Password = currentSapak.password;
            phone1.Text = currentSapak.phone;
            phone2.Text = currentSapak.mobile;
            area.Text = currentSapak.area;
            
        }



        private string GetUniqueID()
        {
            string tmpID = string.Empty;
            int lastvalue = 1;
            string sapakID = string.Empty;
            formula _formula;

            var formulas = (from x in _entities.formulae where x.bo == "SapakFormula" select x);


            if (formulas.Count<formula>() == 0)
            {
                sapakID = lastvalue.ToString("0000");
                _formula = new formula();
                _formula.bo = "SapakFormula";
                _formula.lastvalue = 1;
                _entities.AddToformulae(_formula);

            }
            else
            {
                lastvalue = (formulas.First<formula>()).lastvalue;
                _formula = formulas.First<formula>();
                sapakID = (lastvalue + 1).ToString("0000");
                _formula.lastvalue = lastvalue + 1;
            }


            try
            {

                _entities.SaveChanges();
                return "SP" + sapakID;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return null;
            }




        }

        private void ToolBar_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void method_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string text = (sender as ComboBox).SelectedItem.ToString();


            if (text == "תשלום חד פעמי")
                paymentLabel.Content = "סכום תשלום";
            else
                paymentLabel.Content = "אחוז תשלום";
        }

        private bool checkmandatoryFields()
        {
            bool isValid = true;

            var validationMessage = new StringBuilder();

            //First Name
            if (ValidationFunctions.IsNullEmpty(sapakname.Text))
            {
                sapakname.IsInvalid = true;
                validationMessage.AppendLine(string.Format(FindResource("VLD001").ToString(), sapakname.Tag));
            }
            //Last Name
            if (ValidationFunctions.IsNullEmpty(sapakType.Text))
            {
                validationMessage.AppendLine(string.Format(FindResource("VLD001").ToString(), sapakType.Tag));
            }

            if (ValidationFunctions.IsNullEmpty(method.Text))
            {
                validationMessage.AppendLine(string.Format(FindResource("VLD001").ToString(), method.Tag));
            }


            if (validationMessage.Length > 0)
            {
                Messages.ShowWarning(validationMessage.ToString(), MessageBoxButton.OK);
                return false;
            }

            return isValid;
        }

        private void onDelete_Click(object sender, RoutedEventArgs e)
        {
            IQueryable<Teek> teeks = null;
            MessageBoxResult result = MessageBox.Show("האם אתה בטוח שאתה רוצה למחוק רישימה זו", "אזהרה", MessageBoxButton.YesNo);

            if (result == MessageBoxResult.Yes)
            {
                if (currentSapak != null)
                {

                    teeks = _entities.Teeks.Where(x => x.Sapak.Id == currentSapak.Id);
                    if (teeks.Count<Teek>() > 0)
                    {
                        MessageBox.Show("לא תוכל למחוק ספק זה בגלל שהוא מקושר לרשימות פעילות אחרות.", "אזהרה", MessageBoxButton.OK);
                        return;
                    }
                    else
                    {
                        _entities.DeleteObject(currentSapak);
                        _entities.SaveChanges();
                        NavigationCenter.ShowSearchPage(NavigationTarget.SapakPage, this);
                    }
                }
            }
        }

    }
}
